package com.zzhardy.log;

import java.util.Arrays;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import com.zzhardy.model.SysOperateLog;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 对指定系统进行日志显示，如需追加，再追加代码,只做开发使用,
 */
@Aspect
@Component
public class LogAllAspect {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(LogAllAspect.class);
    
    @Pointcut("execution(public * com.zzhardy.controller.*.*(..))")
    public void webLog(){}
    
    @Before("webLog()")
    public void deBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
    }
    
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
    }
    
    /**
     * 后置异常处理
     */
    @AfterThrowing("webLog()")
    public void throwss(JoinPoint jp){
        // 接收到请求，记录请求内容
    }
    
    /**
     * 后置最终通知,final增强，不管是抛出异常或者正常退出都会执行
     */
    @After("webLog()")
    public void after(JoinPoint jp){
    }
    
    /**
     * 环绕通知,环绕增强，相当于MethodInterceptor
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("webLog()")
    public Object arround(ProceedingJoinPoint pjp) throws Throwable{
        try {
            SysOperateLog sysOperateLog = new SysOperateLog();
            //读取中的用户
            HttpServletRequest request      = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String url = String.format("URL : %s%s Request Method : %s",
                                       request.getRequestURL().toString(),
                                       StringUtils.isNotBlank(request.getQueryString()) ? "?" + request.getQueryString() : "",
                                       request.getMethod());
            sysOperateLog.setUrl(url);
            sysOperateLog.setSysId(100);
            sysOperateLog.setUnitId(100);
            sysOperateLog.setCreateId(100);
            sysOperateLog.setMethod( pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());
            sysOperateLog.setArgs(request.getQueryString());
            sysOperateLog.setIp(request.getRemoteAddr());
            sysOperateLog.setCreateTime(new Date());
            // 所有的日志信息，展示不进行添加，如有需要，开启测试
            //sysOperateLogDao.insert(sysOperateLog);
            
            Object o =  pjp.proceed();
            return o;
        } catch (Throwable e) {
            throw e;
        }
    }
}